        dojo.require('dojo.parser');
        dojo.require('dojo.data.ItemFileReadStore');
        dojo.require('dojo.data.ItemFileWriteStore');
        dojo.require("dojox.grid.compat._grid.edit");
        dojo.require('dojox.grid.DataGrid');
		
        dojo.require('dijit.form.Button');
        dojo.require("dijit.Dialog");
        dojo.require("dijit.form.TextBox");
        dojo.require("dijit.form.SimpleTextarea");
        dojo.require("dijit.form.Textarea");
        dojo.require("dijit.form.FilteringSelect");

        var tributesMasterArray = new Array();
        var bulletpointsMasterArray = new Array();

        // build and initialize arrays for ItemFileWriteStores
        var tributesData = {
            identifier: "tribute_name",
            label: 'Name',
            items: tributesMasterArray
        };

        var bulletpointsData = {
            identifier: 'id',
            label: 'id',
            items: []
        };

        // select no florist at start
        var iSelectedTribute = -1;
        var iSelectedbulletpoint = -1;

        var idx = 0;
        // stuff needed to define catalog grid
		
        var tributesQuery = { tribute_name: '*'};
        var bulletpointsQuery = { id: '*'};

        var tributesGrid = null;
        var bulletpointsGrid = null;
        var data_has_changed = false;

//////////////////////////////////////////////////////////////////////////////////////////////////////////

        function getTributeBulletPoints(idx)
        {
			if(idx >= 0 && idx < bulletpointsMasterArray.length) 
				return bulletpointsMasterArray[idx].bullet_points;
			return null;
        }

        function tributeHasBeenSelected(e)
        {
			var st = getSelectedTribute();
            var i = e.rowIndex;
			iSelectedTribute = i;
			var bulletpoints = getTributeBulletPoints(i);
			if (bulletpoints)
			{
                bulletpointsData.items = bulletpoints;
                bulletpointsGrid.store.close();
                bulletpointsGrid.setStore(new dojo.data.ItemFileWriteStore({data:bulletpointsData}));
			}
			else 
			{
                bulletpointsData.items = [];
                bulletpointsGrid.store.close();
                bulletpointsGrid.setStore(new dojo.data.ItemFileWriteStore({data:bulletpointsData}));
			}
        }

        function getSelectedTribute()
        {
            var items = tributesGrid.selection.getSelected();
            if(items.length<1) return null;
            return items[0];
        }

        function getSelectedBulletPoints()
        {
            var items = bulletpointsGrid.selection.getSelected();
            if(items.length<1) return null;
            return items[0];
        }

        function bulletPointHasChanged(item, attribute, oldValue, newValue)
        {
            if( oldValue == newValue ) return;
            if( attribute == 'total' ) return;
            var itemPrice = cartGrid.store.getValue( item, 'price' );
            var itemQty = cartGrid.store.getValue( item, 'qty' );
            var newTotal = itemPrice * itemQty;
            cartGrid.store.setValue( item, 'total', newTotal );
			updateCartItemsField();
        }
		
        function gridDblClkHandler(e)
        {
            return true;
        }
		
        function addNewBulletPoint()
        {
			// just adds a row to the bullet point grid
			// first, get selected tribute
			var selectedTribute = getSelectedTribute();
			if(null == selectedTribute)
			{	
				alert('You must select a tribute to add bullet points to');
				return;
			}
			var bulletPoints = getTributeBulletPoints(iSelectedTribute);
			if(null == bulletPoints) return;
			
			var new_bullet_point = { id:idx++, bullet_point:''};
			var newBulletNum = bulletPoints.length+1;
			new_bullet_point.bullet_point = 'Bullet Point ' + newBulletNum;
			bulletpointsGrid.store.newItem( new_bullet_point );
			
            data_has_changed = true;
        }

        function updateBulletPoint()
        {
            data_has_changed = true;
        }

        function removeSelectedBulletPoint()
        {
            var selection = getSelectedBulletPoints();
            if(null == selection)
            {
                alert("You must select at least one bullet point first");
            }

            bulletpointsGrid.store.deleteItem(selection);
            bulletpointsGrid.store.fetch();
            bulletpointsGrid.update();

            data_has_changed = true;
        }

        function getTributesAndBulletPoints()
        {
            dojo.xhrGet( {
                url:'/index/tributepackages',
                handleAs: 'json',
                load: function(tributes) {

                    tributesMasterArray = new Array();
                    bulletpointsMasterArray = new Array();
                    if(null != tributes)
                    {
                        for( var i=0; i < tributes.length; i ++ )
                        {
                            var tribute = tributes[i];

                            var nc = {
                                tribute_name:tribute.name
                            };

							console.log('tribute:'+tribute.name);
							
                            tributesMasterArray[i] = nc;
                            bulletpointsMasterArray[i] = { tribute_id:i, bullet_points:[] };

                            var bullet_points = tribute.bullet_points;
                            var bulletPtId = 0;
                            for( var j=0; j < bullet_points.length; j++ )
                            {
                                bulletPtId++;
                                var bullet_point = bullet_points[j];

                                var nb = {
                                    tribute_id:i,
									id:idx++,
                                    bullet_point:bullet_point.name
                                };

                                bulletpointsMasterArray[i].bullet_points[j] = nb;
								console.log(nb);
                            }
                        }
                    }
					
                    // reload the florists grid
                    tributesData.items = tributesMasterArray;
                    tributesGrid.store.close();
                    tributesGrid.selection.clear();
                    tributesGrid.setStore(new dojo.data.ItemFileReadStore({data:tributesData}));

                    // reload the collections grid
                    bulletpointsData.items = [];
                    bulletpointsGrid.store.close();
                    bulletpointsGrid.setStore(new dojo.data.ItemFileWriteStore({data:bulletpointsData}));
                }
            } );
        }

        function saveTributesAndBulletPoints()
        {
            var result = false;

            var xmlstr = '<tributes>';

            for(var i=0; i < tributesMasterArray.length; i++ )
            {
                var tribute = tributesMasterArray[i];

                xmlstr = xmlstr + '<tribute>';
				xmlstr = xmlstr + '<name>' + tribute.tribute_name + '</name>';
                xmlstr = xmlstr + '<bulletpoints>';
				
                var bulletpoints = getTributeBulletPoints( i );
                for( var j=0; j < bulletpoints.length; j++ )
                {
					xmlstr = xmlstr + '<bulletpoint>';
					xmlstr = xmlstr + '<name>' + bulletpoints[j].bullet_point + '</name>';
					xmlstr = xmlstr + '</bulletpoint>';
                }
                xmlstr = xmlstr + '</bulletpoints>';
                xmlstr = xmlstr + '</tribute>';
            }
            xmlstr = xmlstr + '</tributes>';
            
            var tributes_hidden_element = document.getElementById('tributesXML');
            tributes_hidden_element.value = xmlstr;
            
            // "submit" the form to wing the florists/collections and branch id to the controller method
            dojo.xhrPost ({
                    // The page that parses the POST request
                    url:'/index/updatetributepackages',

                    // Name of the Form we want to submit
                    form: 'updateform',

                    // handle reply as JSON
                    handleAs: 'json',

                    // Loads this function if everything went ok
                    load: function (data) {
                            // Put the data into the appropriate <div>
                            console.log(data.status);
							console.log(data.results);
                            if(data.status == "OK")
                                result = true;
                            else
                                result = false;

                    },
                    // Call this function if an error happened
                    error: function (error) {
                            console.error ('Error: ', error);
                    }
                }
            );

            return result;
        }

        var tributesStore = new dojo.data.ItemFileReadStore({data:tributesData});
        var bulletpointsStore = new dojo.data.ItemFileWriteStore({data:bulletpointsData});

        dojo.addOnLoad( function() {

        dojo.connect(dijit.byId("btnNewBulletPoint"), "onClick", addNewBulletPoint );
        dojo.connect(dijit.byId("btnDeleteBulletPoint"), "onClick", removeSelectedBulletPoint );

        tributesGrid = dijit.byId('tributesGrid');
        bulletpointsGrid = dijit.byId('bulletpointsGrid');

        dojo.connect( tributesGrid, "onRowClick", tributeHasBeenSelected );
		
        dojo.connect( bulletpointsGrid, "onCellDblClick", gridDblClkHandler );
        dojo.connect( bulletpointsGrid.store, "onSet", bulletPointHasChanged );

        getTributesAndBulletPoints();
    });



